import React, { useState, useEffect } from 'react'
import './App.scss'
import GoodsItem from './components/GoodsItem'
import MyFooter from './components/MyFooter'
import MyHeader from './components/MyHeader'
import initState from './data'

export default function App() {
  const [list, setList] = useState(() => {
    // 里面这个函数其实只会执行一次，就是初始化的时候
    return JSON.parse(localStorage.getItem('LIST')) || initState
  })

  const changeState = (id) => {
    setList(
      list.map((item) => {
        if (item.id === id) {
          return {
            ...item,
            goods_state: !item.goods_state,
          }
        } else {
          return item
        }
      })
    )
  }

  // !#1 父组件准备修改状态的方法并传递给子组件
  const changeAll = (goods_state) => {
    // !#3 父组件根据接收到的数据做相应的操作
    setList(
      list.map((item) => ({
        ...item,
        goods_state,
      }))
    )
  }

  // 持久化
  // 1. list 变化后存储到本地
  // 2. 初始化 list 数据的时候，本地有就用本地的，否则给个默认数据
  useEffect(() => {
    localStorage.setItem('LIST', JSON.stringify(list))
  }, [list])
  return (
    <div className='app'>
      <MyHeader />
      {list.map((item) => (
        <GoodsItem key={item.id} {...item} changeState={changeState} />
      ))}
      <MyFooter list={list} changeAll={changeAll} />
    </div>
  )
}
